<template>
    <div>
        <van-nav-bar 
            title="修改昵称" 
            left-text="返回" 
            right-text="确认修改" 
            left-arrow 
            @click-left="$router.go(-1)" 
            @click-right="onClickRight" 
        />
        <van-form ref="formRef">
            <van-cell-group>
                <van-field 
                    v-model="nickname" 
                    name="nickname"
                    label="新昵称" 
                    placeholder="请输入..." 
                    maxlength="8" 
                    show-word-limit
                    :rules="[{
                        required: true, 
                        message: '只允许字母、数字、下划线和汉字',
                        pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
                        trigger: 'onBlur'
                    }]"
                />
            </van-cell-group>
        </van-form>
    </div>
</template>

<script>
    import { mapActions, mapMutations, mapState } from 'vuex';

    export default {
        data() {
            return {
                nickname: '',
            }
        },
        computed: {
            ...mapState(['user']),
        },
        methods: {
            ...mapMutations(['upNickname']),
            ...mapActions('myInfo', ['modifyNickname']),
            async onClickRight() {
                try {
                    await this.$refs.formRef.validate();
                    let res = await this.modifyNickname({ user_id: this.user._id, nickname: this.nickname });

                    console.log('修改昵称结果', res);

                    this.upNickname(this.nickname);
                    this.$toast.success('修改成功！');
                    this.$router.go(-1);
                } catch (error) {
                    console.log('校验失败', error);
                }
            },
        },    
    }
</script>